use std::borrow::Cow;

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
};

use crate::{
    error::{AppErr, ErrInfo}, server::header,
};

use super::make_response;

impl IntoResponse for AppErr {
    fn into_response(self) -> Response {
        make_response(|| {
            let info = match self {
                AppErr::Custom(info) => info,
                _ => ErrInfo {
                    err_code: -1,
                    err_msg: Cow::Owned(self.to_string()),
                },
            };
            let mut resp = serde_cbor::to_vec(&info)?.into_response();
            *resp.status_mut() = StatusCode::OK;
            resp.headers_mut().insert(header::API_RESP, header::VAL_API_ERR);
            Ok(resp)
        })
    }
}
